// pages/history/history.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    historyList: [],
    filteredHistoryList: [],
    searchKeyword: '',
    isLoading: true,
    tabBarActive: 2, // 在custom-tab-bar中的位置
    source: 'cocktail_history'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      source: options.source || 'cocktail_history'
    });
    this.loadAllHistory();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 每次显示页面时重新加载历史记录，确保数据是最新的
    this.loadAllHistory();
    
    // 设置TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: this.data.tabBarActive
      });
    }
  },

  /**
   * 加载所有历史记录
   */
  loadAllHistory: function() {
    this.setData({
      isLoading: true
    });
    
    try {
      const key = this.data.source === 'perfume_history' ? 'perfume_history' : 'cocktail_history';
      const historyList = wx.getStorageSync(key) || [];
      this.setData({
        historyList: historyList,
        filteredHistoryList: historyList,
        isLoading: false
      });
    } catch (e) {
      console.error('获取历史记录失败:', e);
      this.setData({
        isLoading: false
      });
      
      wx.showToast({
        title: '加载历史记录失败',
        icon: 'none'
      });
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput: function(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    this.filterHistoryList(keyword);
  },

  /**
   * 清空搜索
   */
  clearSearch: function() {
    this.setData({
      searchKeyword: '',
      filteredHistoryList: this.data.historyList
    });
  },

  /**
   * 根据关键词过滤历史记录
   */
  filterHistoryList: function(keyword) {
    if (!keyword) {
      this.setData({
        filteredHistoryList: this.data.historyList
      });
      return;
    }
    
    const keywordLower = keyword.toLowerCase();
    const filtered = this.data.historyList.filter(item => {
      // 仅根据鸡尾酒名称进行搜索
      return item.name && item.name.toLowerCase().includes(keywordLower);
    });
    
    this.setData({
      filteredHistoryList: filtered
    });
  },

  /**
   * 查看历史配方详情
   */
  viewHistoryDetail: function(e) {
    const index = e.currentTarget.dataset.index;
    const historyItem = this.data.filteredHistoryList[index];
    
    // 找到原始数据中的索引
    const originalIndex = this.data.historyList.findIndex(item => 
      item.timestamp === historyItem.timestamp
    );
    
    if (originalIndex !== -1) {
      let url = '/pages/result/result?id=' + originalIndex;
      if (this.data.source === 'perfume_history') {
        url += '&source=perfume_history';
      }
      wx.navigateTo({ url });
    }
  },

  /**
   * 显示清空确认对话框
   */
  showClearConfirm: function() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有历史记录吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          this.clearHistory();
        }
      }
    });
  },

  /**
   * 清空历史记录
   */
  clearHistory: function() {
    wx.setStorageSync(this.data.source, []);
    this.setData({
      historyList: [],
      filteredHistoryList: [],
      searchKeyword: ''
    });
    
    wx.showToast({
      title: '历史记录已清空',
      icon: 'success'
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '我的鸡尾酒特调历史 - 今日微醺',
      path: '/pages/index/index',
      imageUrl: this.data.historyList.length > 0 ? this.data.historyList[0].image : ''
    };
  }
}); 